Java 26일 코스 - Day 5: 반복문

Day 5: 반복문

반복문은 동일한 코드를 여러 번 실행할 때 사용합니다. Java에서는 for, while, do-while 세 가지 반복문을 제공합니다. 반복 횟수가 정해져 있으면 for, 조건에 따라 반복하면 while을 주로 사용합니다.

for 문

반복 횟수가 명확할 때 가장 많이 사용하는 반복문입니다.

public class ForLoopExample {
    public static void main(String[] args) {
        // 기본 for문: 1부터 10까지 출력
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 역순 반복
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 2씩 증가
        for (int i = 0; i <= 20; i += 2) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 구구단 2단
        int dan = 2;
        for (int i = 1; i <= 9; i++) {
            System.out.println(dan + " x " + i + " = " + (dan * i));
        }
    }
}

while과 do-while

조건을 기반으로 반복할 때 사용합니다. do-while은 최소 한 번은 실행됩니다.

public class WhileExample {
    public static void main(String[] args) {
        // while: 조건을 먼저 확인
        int sum = 0;
        int num = 1;
        while (num <= 100) {
            sum += num;
            num++;
        }
        System.out.println("1~100 합계: " + sum); // 5050

        // do-while: 최소 한 번 실행 후 조건 확인
        int count = 0;
        do {
            System.out.println("실행 횟수: " + (count + 1));
            count++;
        } while (count < 3);

        // 무한 루프 (의도적 사용)
        int attempt = 0;
        while (true) {
            attempt++;
            System.out.println("시도 " + attempt);
            if (attempt >= 5) {
                System.out.println("최대 시도 도달, 종료!");
                break;
            }
        }
    }
}

중첩 반복문

반복문 안에 반복문을 넣어 2차원 패턴을 만들 수 있습니다.

public class NestedLoop {
    public static void main(String[] args) {
        // 구구단 전체
        for (int dan = 2; dan <= 9; dan++) {
            System.out.println("=== " + dan + "단 ===");
            for (int i = 1; i <= 9; i++) {
                System.out.println(dan + " x " + i + " = " + (dan * i));
            }
            System.out.println();
        }

        // 별 삼각형 패턴
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        // *
        // * *
        // * * *
        // * * * *
        // * * * * *
    }
}

break와 continue

반복문의 흐름을 제어하는 키워드입니다.

public class BreakContinue {
    public static void main(String[] args) {
        // break: 반복문 즉시 탈출
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                System.out.println("6에서 중단!");
                break;
            }
            System.out.print(i + " "); // 1 2 3 4 5
        }
        System.out.println();

        // continue: 현재 반복 건너뛰기
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue; // 3의 배수 건너뛰기
            }
            System.out.print(i + " "); // 1 2 4 5 7 8 10
        }
        System.out.println();

        // 레이블을 이용한 중첩 루프 탈출
        outer:
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                if (i * j > 10) {
                    System.out.println("i=" + i + ", j=" + j + "에서 탈출");
                    break outer;
                }
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}

오늘의 연습문제

  1. 소수 판별기: 2부터 100까지의 숫자 중 소수(prime number)만 출력하는 프로그램을 작성하세요. 중첩 for문과 break를 활용하세요.

  2. 역삼각형 별 패턴: 높이가 5인 역삼각형 별 패턴을 출력하세요. (첫 줄에 별 5개, 마지막 줄에 별 1개)

  3. 숫자 야구 시뮬레이션: 정답 숫자(예: 42)를 미리 설정하고, 1부터 100까지 1씩 증가하면서 정답을 찾는 프로그램을 작성하세요. 정답을 찾으면 시도 횟수를 출력하고 반복을 종료하세요.

이 글이 도움이 되었나요?